<?php

/* 扩展ci的核心系统类 */
class Entity extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    // 将实体类的定义的表实体表单验证转为数组。
    public function to_array()
    {
        // $arr = (array)$this;
        $arr = json_decode(json_encode($this),true);
        $ret =  array();
        foreach($arr as $item){
            $ret [] = $item;
        }
        return $ret;
    }

    /* 实体类 自带的表单验证
    *
    *@params fields 要验证的字段列表，string，array。不填则验证整个entity
    *@params datas 要验证的数据，不填则默认使用input的post
     */
    public function valid($fields=null,$datas=null)
    {
        $that =& get_instance();

        $that->load->library('form_validation');

        /* set data */
        $data = array();
        if($datas && is_array($datas)){
            $data = $datas;
        }else{
            $data = $that->input->post();
        }
        $that->form_validation->set_data($data);

        /* set rules */
        $rules = array();
        $entityRules = $this->to_array();
        if($fields){
            $fields = is_array($fields) ? $fields : array($fields);
           
            foreach($entityRules as $value){
                if(in_array($value['field'],$fields)){
                    $that->form_validation->set_rules(array($value));
                }
            }
        }else{
            $that->form_validation->set_rules($entityRules);
        }
        // return $entityRules;
        // return  $that->form_validation->has_rule('userName');

        $valid = $that->form_validation->run();
        // echo json_encode($rules);
        $ret = array("result"=>$valid,"error" => array());
        if (!$valid) {
            $ret['error'] = $that->form_validation->error_array();
        }
        $that->form_validation->reset_validation();
        return $ret;
    }
}
